<?php
/**
 * 订单接口类
 * @package  module/eai/bill
 * @author   dongleixin <dongleixin@ebsig.com>
 * @version 1.0
 * @date     2017-2-24
 */

namespace App\Service\Rpc\Erp;

use Carbon\Carbon;

use GuzzleHttp\Client;

use App\Models\Bill\Bill;  //订单主表

use App\Models\Bill\BillPay;

use App\Models\Bill\LogEaiBill;

use App\Models\Bill\BillGoods; //订单商品表

use App\Models\Customer\Customer;

class FcmyErp
{

    /**
     * 接口请求地址
     */
    private $http_url = BILL_GATEWAY;

    private $bill_no = 0;

    private $password = AUTH_PASSWORD;

    /**
     * 请求接口，并保存日志
     * @param string $request_url 请求链接
     * @param string $api_name 接口名称
     * @param array $get_data get请求数据
     * @param array $post_data post请求数据
     * @param string $request_way 请求方式
     * @return array('code'=>'','message'=>'','data'=>'')
     */
    public function requestApi( $request_url, $api_name ,$get_data = array(), $post_data = array(), $request_way = 'get')
    {


        $client = new Client();

        //md5见字符串
        $get_str = '';

        if ( $get_data ) {

            ksort($get_data);  //参数按键值字典序排列

            $temp_str = '';

            foreach ($get_data as $key => $val) {
                $temp_str .= $val;
            }

            if ( $post_data ) {

                $get_str = md5($temp_str . $this->password . json_encode($post_data));

            } else {
                $get_str = md5($temp_str . $this->password);
            }

        }

        //接口请求开始时间
        $start_time = microtime(true);

        if ( $request_way == 'get') {

            $get_data['md5'] = $get_str;

            $res = $client->get($request_url , [
                'headers' =>[
                    'Accept' => 'application/json',
                    'Content-Type' => 'multipart/form-data;charset=utf-8',
                ],
                'auth' =>['guest', 'guest'],
                'query' => $get_data,
                'connect_timeout' => 3,
                'timeout' => 10,

            ]);

        } else  {

            if (!empty($get_data)) {
                $get_data_str = '?' . http_build_query($get_data) .'&md5=' . $get_str;
            } else {
                $get_data_str =  '?md5=' . $get_str;
            }

            $post_data_json = json_encode($post_data);

            $res = $client->post($request_url.$get_data_str,['form_params'=>[
                'headers' =>[
                    'Accept' => 'application/json',
                    'Content-Type' => 'multipart/form-data;charset=utf-8',
                ],
                'auth' =>['guest', 'guest'],
                'data' => $post_data_json,
                'connect_timeout' => 3,
                'timeout' => 10,
            ]]);

        }

        //接口请求结束时间
        $end_time = microtime(true);

        $result_array = json_decode($res->getBody(),true);

        $return_data = array();

        if ($res->getStatusCode() == 200 && isset($result_array['status'])) {

            if ( $result_array['status'] == 20000 ) {    //接口请求返回参数 20000状态为推送成功

                $return_data['code']=200;
                $return_data['message'] ='ok';
                $return_data['data'] = $result_array;

            } else {

                $return_data['code']=$result_array['status'];
                $return_data['message'] ='接口调用失败';
                $return_data['data'] = $result_array;

            }

        } else {

            $return_data['code']= 404;
            $return_data['message'] ='接口调用失败';
            $return_data['data'] = '';

        }

        //记录日志
        $log_eai_bill = new LogEaiBill();
        $log_eai_bill->uuid = makeUuid();
        $log_eai_bill->timeStamp = Carbon::now();
        $log_eai_bill->creator = 'haitun';
        $log_eai_bill->createTime = Carbon::now();
        $log_eai_bill->bill_no = $this->bill_no;
        $log_eai_bill->api_name = $api_name;
        if ( $request_way == 'get' ) {
            $log_eai_bill->request_data = print_r($get_data, true);
        } else {
            $log_eai_bill->request_data = print_r($post_data, true);
        }
        $log_eai_bill->return_data = print_r($return_data, true);
        $log_eai_bill->return_code = $return_data['code'];
        $log_eai_bill->return_msg  = $return_data['message'];
        $log_eai_bill->exec_time = ($end_time - $start_time) * 1000;
        $log_eai_bill->save();

        return $return_data;

    }

    /**
     * 获取临时令牌
     * @return array
     */
    public function token()
    {

        $get_data = array(
            'type' => 'token',
            'name' =>AUTH_NAME,
            'time' =>time(),
            'debug' => 'on'
        );

        $request_result = $this->requestApi( $this->http_url, 'token' , $get_data, array(), 'get');

        if( $request_result['data']['status'] == 20000 ){
            return array( 'code' => 200, 'message' => 'ok', 'data' => $request_result['data']);
        }else{
            return array( 'code' => 400, 'message' => '接口调用失败', 'data' => $request_result['data'] );
        }

    }

    /**
     * 推送订单信息
     * @param $bill_data
     * @return array
     */
    public function pushBillToErp( $bill_data )
    {

        $this->bill_no = $bill_data['bill_no'];

        $bill_data = json_decode($bill_data['jsonStr'],true);

        $return_data = $this->token();

        if( $return_data['code'] == 200 ) {
            $name = $return_data['data']['data']['name'];
            $this->password = $return_data['data']['data']['key'];
        }else{
            $name = AUTH_NAME;
        }

        $get_data = array(
            'type' => 'pushOrderDataInfo',
            'name' =>$name,
            'time' =>time(),
            'debug' => 'on'
        );

        $request_result = $this->requestApi( $this->http_url, 'pushOrderDataInfo' , $get_data, $bill_data, 'post:json');

        if ( $request_result['code'] == 200 ) {

            return array('code' => 200, 'message' => 'ok', 'data' => $request_result['data']);
        } else {
            return array('code' => 400, 'message' => $request_result['message']);
        }
    }


    /**
     * 订单取消
     * @param $bill_data
     * @return array
     */
    public function cancelBill( $bill_data )
    {

        if ( !isset($bill_data['bill_no']) || empty($bill_data['bill_no']) ) {
            return array('code' => 400, 'message' => '订单不能为空');
        }

        $bill_master = Bill::find($bill_data['bill_no']);
        if ( !$bill_master ) {
            return array('code' => 400, 'message' => '订单信息不存在');
        }

        $this->bill_no = $bill_data['bill_no'];

        $return_data = $this->token();

        if( $return_data['code'] == 200 ) {
            $name = $return_data['data']['data']['name'];
            $this->password = $return_data['data']['data']['key'];
        }else{
            $name = AUTH_NAME;
        }

        $get_data = array(
            'type' => 'cancelOrder',
            'name' =>$name,
            'time' =>time(),
            'debug' => 'on'
        );

        $bill_data = array(
            'data' => array(
                array(
                    'orderSn' => $bill_data['bill_no'],
                ),
            )
        );

        $request_result = $this->requestApi( $this->http_url, 'cancelOrder' , $get_data, $bill_data, 'post:json');

        if ( $request_result['code'] == 200 ) {

            return array('code' => 200, 'message' => 'ok', 'data' => $request_result['data']);
        } else {
            return array('code' => 400, 'message' => $request_result['message']);
        }

    }


    /**
     * 查询订单状态接口
     * @param $bill_data
     * @return array
     */
    public function getOrderStatus( $bill_data )
    {

        if ( !isset($bill_data['bill_no']) || empty($bill_data['bill_no']) ) {
            return array('code' => 400, 'message' => '订单不能为空');
        }

        $bill_master = Bill::find($bill_data['bill_no']);
        if ( !$bill_master) {
            return array('code' => 400, 'message' => '订单信息不存在');
        }

        $this->bill_no = $bill_data['bill_no'];

        $return_data = $this->token();

        if( $return_data['code'] == 200 ) {
            $name = $return_data['data']['data']['name'];
            $this->password = $return_data['data']['data']['key'];
        }else{
            $name = AUTH_NAME;
        }

        $get_data = array(
            'type' => 'getOrderStatus',
            'name' =>$name,
            'time' =>time(),
            'debug' => 'on'
        );

        $bill_data = array(
            'data' => array(
                'orderSn' => $bill_data['bill_no']
            )
        );

        $request_result = $this->requestApi( $this->http_url, 'getOrderStatus' , $get_data, $bill_data, 'post:json');

        if ( $request_result['code'] == 200 ) {

            return array('code' => 200, 'message' => 'ok', 'data' => $request_result['data']);
        } else {
            return array('code' => 400, 'message' => $request_result['message']);
        }

    }


    /**
     * 查询订单物流信息接口
     * @param $bill_data
     * @return array
     */
    public function getLogisticsInfo( $bill_data )
    {

        if ( !isset($bill_data['bill_no']) || empty($bill_data['bill_no']) ) {
            return array('code' => 400, 'message' => '订单不能为空');
        }

        $bill_master = Bill::find($bill_data['bill_no']);
        if ( !$bill_master) {
            return array('code' => 400, 'message' => '订单信息不存在');
        }

        $this->bill_no = $bill_data['bill_no'];

        $return_data = $this->token();

        if( $return_data['code'] == 200 ) {
            $name = $return_data['data']['data']['name'];
            $this->password = $return_data['data']['data']['key'];
        }else{
            $name = AUTH_NAME;
        }

        $get_data = array(
            'type' => 'getLogisticsInfo',
            'name' =>$name,
            'time' =>time(),
            'debug' => 'on'
        );

        $bill_data = array(
            'data' => array(
                'orderSn' => $bill_data['bill_no']
            )
        );

        $request_result = $this->requestApi( $this->http_url, 'getLogisticsInfo' , $get_data, $bill_data, 'post:json');

        if ( $request_result['code'] == 200 ) {

            return array('code' => 200, 'message' => 'ok', 'data' => $request_result['data']);
        } else {
            return array('code' => 400, 'message' => $request_result['message']);
        }

    }

    /**
     * 创建订单推送数据
     * @param $bill_data
     * @return array
     */
    public function createBillPushData($bill_data)
    {

        //查询订单商品数据
        $search_goods_data = BillGoods::where('bill_no',$bill_data['bill_no'])->get()->toArray();
        if ( empty($search_goods_data) ) {
            return array('code'=>404,'message'=>'没有找到订单商品数据');
        }

        //商品信息
        $goods_data = array();

        //订单总金额
        $total_money  = $bill_data['bill_payable']+$bill_data['bill_balance_money'] + $bill_data['deliver_fee'];

        foreach ( $search_goods_data as $key=>$goods ){

            $goods_data[] = array(
                'quantity' => $goods['goods_amount'],
                'goodsName' => $goods['goods_name'],
                'goodsSn' => $goods['product_code'],
                'goodsPrice' => $goods['goods_purchasePrice'],
            );

        }

        /**
         * 查询订单支付信息
         */
        $billPays = BillPay::select('payTypeName','pay_time','pay_amount','pay_code','type','payTypeID')->where('bill_no',$bill_data['bill_no'])->get()->toArray();
        if ( empty($billPays) ) {
            return array('code'=>404,'message'=>'没有找到订单支付数据');
        }

        /**
         * 查询订单会员信息
         */
        $cust_data = Customer::find($bill_data['pcustID']);
        if( empty($cust_data) ){
            return array('code'=>404,'message'=>'没有找到订单会员数据');
        }

        //订单平台
        $bill_platform_name = '';
        if ( $bill_data['billPlatform'] == 1 ) {
            $bill_platform_name = '自营';
        } else if ( $bill_data['billPlatform'] == 2 ) {
            $bill_platform_name = '天猫';
        } else if ( $bill_data['billPlatform'] == 3 ) {
            $bill_platform_name = '京东';
        } else if ( $bill_data['billPlatform'] == 4 ) {
            $bill_platform_name = '淘宝';
        } else if ( $bill_data['billPlatform'] == 5 ) {
            $bill_platform_name = '百度外卖';
        }

        //推送数据数组
        $bill_push_data = array(
            'data' => array(
                array(
                    'orderSn' => $bill_data['bill_no'],
                    'consignee' => $bill_data['deliver_name'],
                    'country' => '中国',
                    'province' => $bill_data['deliver_province'],
                    'city' => $bill_data['deliver_city'],
                    'district' => $bill_data['deliver_county'],
                    'address' => $bill_data['deliver_address'],
                    'zipcode' => '',
                    'tel' => $bill_data['deliver_phone'] != '' ? $bill_data['deliver_phone'] : $bill_data['deliver_mobile'],
                    'mobile' => $bill_data['deliver_mobile'],
                    'idCardNumber' => $cust_data->identification_card,
                    'siteType' => $bill_platform_name,
                    'siteName' => '',
                    'consumerNote' => $bill_data['remark'],
                    'shippingFee' => $bill_data['deliver_fee'],
                    'orderAmount' => $total_money,
                    'moneyPaid' => $bill_data['bill_payable'],
                    'paymentInfoName' => $bill_data['deliver_name'],
                    'paymentInfoIdCardNumber' => $cust_data->identification_card,
                    'paymentInfoMethod' => $billPays[0]['payTypeName'],
                    'paymentInfoNumber' => $billPays[0]['pay_code'],
                    'paymentAccount' => 'htdolphin@163.com',
                    'isCheck' => 'no',
                    'items' =>$goods_data,
                )
            ),
        );

        return array('code'=>200 , 'messsage'=>'ok', 'data'=>$bill_push_data);

    }

}